// shopMallPackage/pages/score/voucherHouseMoney/voucherHouseMoney.js
import { voucherHouseAction, getMyWallet } from "../../../../service/onetoone_service"
import debounce from "../../../../tools/debounce"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      deductIntegral: "",
      roleConfig: {},// 角色配置项
      allWithDrawMoney: 0,//全部可抵扣金额
      balanceMoney: 0,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      roleConfig: app.globalData.roleConfig,
    })
    this.myWalletInfo();
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  pushToIncome() {
    wx.navigateTo({
      url: '/storePackage/pages/calculusDetail/calculusDetail',
    })
  },
  inputAction(e) {
    this.setData({
      'formData.deductIntegral': e.detail.value
    })
  },
  applyAction() {
    if (!this.data.formData.deductIntegral) {
      wx.showToast({
        title: '抵扣金额不能为空',
        icon: "none"
      })
      return;
    }
    if (this.data.formData.deductIntegral > this.data.allWithDrawMoney) {
      wx.showToast({
        title: '抵扣金额不能大于可抵扣金额',
        icon: "none"
      })
      return;
    }
    debounce(this.applyRequest)
  },
  applyRequest() {
    wx.showLoading();
    voucherHouseAction(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '申请成功',
          icon: "success"
        })
        this.myWalletInfo();
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
        this.setData({
          'formData.deductIntegral': 0,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:申请抵扣失败了:", err);
      wx.showToast({
        title: err || '操作失败',
        icon: "none",
        duration: 4000,
      })
    })
  },

  //获取我的积分数据:
  myWalletInfo() {
    getMyWallet().then(res => {
      console.log("JJLog:钱包数据===:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          balanceMoney: res.data.restMoney || 0,
        })
        let houseDeductRatio = 0;
        if (this.data.roleConfig.houseDeductRatio) {
          houseDeductRatio = this.data.roleConfig.houseDeductRatio;
        }
        let setMoeny = Math.floor((this.data.balanceMoney * (100 - houseDeductRatio)) / 100)
        this.setData({
          allWithDrawMoney: setMoeny,
        })
        app.globalData.balanceMoney = this.data.balanceMoney;
      }
    }).catch(err => {
      console.error("JJLog:getMyWallet", err);
    })
  },
  inputAllAction() {
    this.setData({
      'formData.deductIntegral': this.data.allWithDrawMoney
    })
  },


})